<%-- 
    Document   : Masterpage_bottom
    Created on : Mar 25, 2013, 2:33:23 PM
    Author     : DinhNP
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<link href="css/bottom.css" type="text/css" rel="stylesheet"/>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>BOTTOM</title>
        <link href="css/bottom.css" type="text/css" rel="stylesheet"/>
        <script type="text/javascript" src="js/commonjs.js" ></script>
        <style>
            .dynamicItem{
                background-image: url(img/dynamicItem.jpg);
                background-repeat: no-repeat;
            }  
        </style>
        <script>
            var index=0;
            var songxml;
            var albumxml;
            var songInDynamicPlayer=[];
            var tempInnerHTML;
            var context = '${pageContext.request.contextPath}';

            function loadSongData(){

                // parse xml to doms
                if(sessionStorage.getItem("songxml")==null ||
                    sessionStorage.getItem("albumxml")==null ){
                    var xml = new XMLSerializer().serializeToString(loadXMLDoc(context+"/xml/Songs.xml"));
                    sessionStorage.setItem("songxml",xml);                    
                    xml = new XMLSerializer().serializeToString(loadXMLDoc(context+"/xml/Albums.xml"));
                    sessionStorage.setItem("albumxml",xml);               
                }

                xml = sessionStorage.getItem("songxml");
                songxml = new DOMParser().parseFromString(xml,"text/xml");
                xml = sessionStorage.getItem("albumxml");
                albumxml = new DOMParser().parseFromString(xml,"text/xml");

                var listStore = JSON.parse(sessionStorage.getItem("dynamicPlayer"));
                if (listStore!=null){
                    
                    for (var i=0;i<listStore.length;i++){                       
                       
                        songInDynamicPlayer = listStore;
                        displayOneDynamicItem(i);
                    }
                }
                
            }

            function displayOneDynamicItem(index){
                var newItem = document.createElement('div');
                var nodeText = document.createTextNode(songInDynamicPlayer[index].songTitle+'-'+
                    songInDynamicPlayer[index].albumTitle );
                var itemContainer = document.createElement('div');
                itemContainer.className = "dynamicItem_container";
                
                newItem.appendChild(nodeText);
                newItem.setAttribute('id', (index));
                newItem.className = "dynamicItem";
                newItem.setAttribute('onclick', 'playSong('+(index)+')');
                newItem.setAttribute('title', nodeText.nodeValue);
                newItem.style.backgroundImage = "url(img/dynamicItem.jpg)";
                itemContainer.appendChild(newItem);

                var removeIcon = new Image();
                removeIcon.src = 'img/closeIcon.png';
                removeIcon.className = "removeItemIcon";
                removeIcon.setAttribute('onclick', 'removeDynamicItem('+index+')');
                removeIcon.setAttribute('title', 'Xóa bài hát');
                itemContainer.appendChild(removeIcon);


                document.getElementById('dynamic_player').appendChild(itemContainer);
                document.getElementsByClassName('subDragZone')[0].innerHTML = 'Tổng số bài hát: '+ songInDynamicPlayer.length;
                if (songInDynamicPlayer.length==1){                    
                    document.getElementById('masterPlayer').src = getSongSourceBySongID(songInDynamicPlayer[0].songID);
                    document.getElementById('masterPlayer').load();
                    document.getElementById(0).style.backgroundImage = 'url(img/dynamicItemPlaying.jpg)';
                    sessionStorage.setItem('itemBefore',0);
                }
            }
            
            function getSongID(str){
                if (str.indexOf("?") > 0)
                {
                    var arrParams = str.split("?");
                    var arrURLParams = arrParams[1].split("&");
                    var arrParamNames = new Array(arrURLParams.length);
                    var arrParamValues = new Array(arrURLParams.length);
                    var i = 0;
                    for (i=0;i<arrURLParams.length;i++)
                    {
                        var sParam =  arrURLParams[i].split("=");
                        arrParamNames[i] = sParam[0];
                        if (sParam[1] != "")
                            arrParamValues[i] = unescape(sParam[1]);
                        else
                            arrParamValues[i] = "No Value";
                    }
                    for (i=0;i<arrURLParams.length;i++)
                    {
                        if(arrParamNames[i] == 'id'){                            
                            return arrParamValues[i];
                        }
                    }
                    return false;
                }
            }
            function isSongExistInPlayer(songID){
                for (var i=0;i<songInDynamicPlayer.length;i++){
                    if (Number(songID)==Number(songInDynamicPlayer[i].songID)){
                        return true;
                    }
                }
                return false;
            }
            function eventEndSong(){
                if (Number(sessionStorage.getItem('itemBefore')==Number(songInDynamicPlayer.length)-1)){
                    var audios = document.getElementById('masterPlayer');
                    audios.pause();
                }else {
                    playSong(Number(sessionStorage.getItem('itemBefore'))+1);
                }
            }
            function addSongToDynamicPlayer(songID){
               
                var listSongs = songxml.getElementsByTagName("Song");
                var audio = document.getElementById('masterPlayer');
                
                for (var i=0;i<listSongs.length;i++){
                    var tempID = listSongs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue;
                    if (Number(tempID)==Number(songID)){
                        var songTitle =listSongs[i].getElementsByTagName("SongTitle")[0].firstChild.nodeValue;
                        var songViews =listSongs[i].getElementsByTagName("SongViews")[0].firstChild.nodeValue;
                        var songDescription =listSongs[i].getElementsByTagName("SongDescription")[0].firstChild.nodeValue;
                        var songSRC =listSongs[i].getElementsByTagName("SongSRC")[0].firstChild.nodeValue;
                        var likeNumber =listSongs[i].getElementsByTagName("LikeNumber")[0].firstChild.nodeValue;
                        var lyrics =listSongs[i].getElementsByTagName("Lyrics")[0].firstChild.nodeValue;
                        if (listSongs[i].getElementsByTagName("AlbumTitle")[0].firstChild!=null){
                            var albumTitle = listSongs[i].getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
                        }else var albumTitle='';                        
                        var albumID = listSongs[i].getElementsByTagName("AlbumID")[0].firstChild.nodeValue;

                        songInDynamicPlayer.push({
                            songID: songID,
                            songTitle: songTitle,
                            songViews: songViews,
                            songDescription: songDescription,
                            songSRC: songSRC,
                            likeNumber:likeNumber,
                            lyrics: lyrics,
                            albumID: albumID,
                            albumTitle: albumTitle
                        });                                                
                    }
                }                
            }
            function getSongSourceBySongID(songID){
                var contextPath='${pageContext.request.contextPath}';
                
                var listSongs = songxml.getElementsByTagName("Song");

                for (var i=0;i<listSongs.length;i++){
                    var tempID = listSongs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue;
                    if (Number(tempID)==Number(songID)){
                        if (listSongs[i].getElementsByTagName("AlbumTitle")[0].firstChild!=null){
                            var albumTitle = listSongs[i].getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
                        }else var albumTitle='';                        
                        var albumID = listSongs[i].getElementsByTagName("AlbumID")[0].firstChild.nodeValue;
                        var songSRC = listSongs[i].getElementsByTagName("SongSRC")[0].firstChild.nodeValue;
                        var albums = albumxml.getElementsByTagName("Album");
                        for(var i = 0;i<albums.length;i++){
                            var albumId = albums[i].getElementsByTagName("AlbumID")[0].firstChild.nodeValue;
                            if(Number(albumId)== Number(albumID)){
                                var artist = albums[i].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
                                var src = contextPath+ "/db/" + artist.removeDotCharacter() + "/Album/" + albumTitle + "/" + songSRC +'.mp3';
                                return src;
                            }
                        }
                    }
                }
            }
            function removeDynamicItem(indexID){
                for (var i=indexID;i<songInDynamicPlayer.length-1;i++){
                    switchDynamicItemByIndex(i, i+1);
                }
                songInDynamicPlayer.splice(songInDynamicPlayer.length-1, 1);
                
                document.getElementById('dynamic_player').innerHTML = '';
                for (var i = 0;i<songInDynamicPlayer.length;i++){
                    displayOneDynamicItem(i);
                }
                sessionStorage.setItem("dynamicPlayer",JSON.stringify(songInDynamicPlayer));
                
                if (sessionStorage.getItem('itemBefore')!=null){
                    if (Number(sessionStorage.getItem('itemBefore'))==Number(indexID)){
                        sessionStorage.removeItem('itemBefore');
                        document.getElementById('masterPlayer').pause();
                        document.getElementById('masterPlayer').src =null;
                        if (indexID>0){
                            document.getElementById('masterPlayer').src = getSongSourceBySongID(songInDynamicPlayer[indexID-1].songID);
                            document.getElementById('masterPlayer').load();
                            document.getElementById(indexID-1).style.backgroundImage = 'url(img/dynamicItemPlaying.jpg)';
                            sessionStorage.setItem('itemBefore',indexID-1);
                        }
                        
                    }else if (Number(sessionStorage.getItem('itemBefore'))<Number(indexID)){
                        document.getElementById(sessionStorage.getItem('itemBefore')).style.backgroundImage = 'url(img/dynamicItemPlaying.jpg)';
                    }else {
                        sessionStorage.setItem('itemBefore',sessionStorage.getItem('itemBefore')-1);
                        document.getElementById(sessionStorage.getItem('itemBefore')).style.backgroundImage = 'url(img/dynamicItemPlaying.jpg)';
                    }
                }
                if(songInDynamicPlayer.length==0){
                    document.getElementsByClassName('subDragZone')[0].innerHTML = 'Kéo thả bài hát ở đây để nghe';
                    document.getElementById('masterPlayer').src = '';
                    
                }
            }
            function switchDynamicItemByIndex(index1, index2){
                temp = songInDynamicPlayer[index1];
                songInDynamicPlayer[index1]=songInDynamicPlayer[index2];
                songInDynamicPlayer[index2]=temp;
                
            }
            function switchSongInPlayerByID(fromID, toID){
                var fromItem;
                var toItem;
                for (var i=0; i<songInDynamicPlayer.length;i++){
                    if (Number(fromID)==Number(songInDynamicPlayer[i].songID)){
                        fromItem = i;
                    }
                    if (Number(toID)==Number(songInDynamicPlayer[i].songID1)){
                        toItem = i;
                    }

                }
                var temp = songInDynamicPlayer[fromItem];
                songInDynamicPlayer[fromItem]=songInDynamicPlayer[toItem];
                songInDynamicPlayer[toItem] = temp;

            }
            function allowDrop(event){
                event.preventDefault();
            }
            function drag(event){
                var data = event.target.href;
                var id = getSongID(data);
                event.dataTransfer.setData("Text",id);

            }

            function drop(event){
                event.preventDefault();
                var id = event.dataTransfer.getData("Text");
                
                if (!isSongExistInPlayer(id)){
                    addSongToDynamicPlayer(id);
                    displayOneDynamicItem(songInDynamicPlayer.length-1);                    
                    sessionStorage.setItem("dynamicPlayer",JSON.stringify(songInDynamicPlayer));                                                            
                }
                           
            }

            function setEventForSong(){
                var songSelector = document.getElementsByClassName("song_item");
                for (var i=0; i<songSelector.length;i++){
                    songSelector[i].setAttribute('draggable', 'true');
                    songSelector[i].setAttribute('ondragstart', 'drag(event)');
                }
            }
            function playSong(idInPlayer){
                resetSetting();
                var sourceToPlay = getSongSourceBySongID(songInDynamicPlayer[idInPlayer].songID);
                var audios = document.getElementById('masterPlayer');                
                
                if (sessionStorage.getItem('itemBefore')==null || Number(sessionStorage.getItem('itemBefore')!=Number(idInPlayer))){
                    if (sessionStorage.getItem('itemBefore')!=null){
                        document.getElementById(sessionStorage.getItem('itemBefore')).style.backgroundImage = 'url(img/dynamicItem.jpg)';
                    }
                    audios.src = sourceToPlay;                    
                    document.getElementById(idInPlayer).style.backgroundImage = "url(img/dynamicItemPlaying.jpg)";                    
                    sessionStorage.setItem('itemBefore',idInPlayer);
                    audios.play();

                }else if (audios.paused||audios.stoped||audios.ended){
                    if (audios.src==''){
                        audios.src = sourceToPlay;
                    }
                    audios.play();
                    document.getElementById(idInPlayer).style.backgroundImage = "url(img/dynamicItemPlaying.jpg)";
                }else if (audios.play){
                    audios.pause();                    
                }
            }
            function backFunction(){
                if (sessionStorage.getItem('itemBefore')!=null){
                    if (Number(sessionStorage.getItem('itemBefore'))!=0){
                        playSong(sessionStorage.getItem('itemBefore')-1);                       
                    }
                }
            }
            function nextFunction(){
                if (Number(sessionStorage.getItem('itemBefore')!=Number(songInDynamicPlayer.length)-1)){
                    playSong(Number(sessionStorage.getItem('itemBefore'))+1);
                }
            }
            function expandCollapsed(){
                var player = document.getElementById("dynamic_player");
                if (player.style.display != 'none'){
                    player.style.display = 'none';
                    document.getElementsByClassName('openClose')[0].src = 'img/expand.png';
                    var control = document.getElementById("dynamic_controls");
                    control.style.position = 'fixed';
                    control.style.bottom = '0px';
                    control.style.right = '0px';
                    document.getElementsByClassName('subDragZone')[0].style.display = 'block';
                }else{
                    player.style.display = 'block';
                    document.getElementsByClassName('openClose')[0].src = 'img/collapse.png';
                    var control = document.getElementById("dynamic_controls");
                    control.style.position = 'relative';
                    document.getElementsByClassName('subDragZone')[0].style.display = 'none';
                }
            }
            function saveCurrentSetting(){
                resetSetting();
                var audios = document.getElementById('masterPlayer');
                if (audios.src!=''){
                    sessionStorage.setItem('currentSRC',audios.src);
                    if(audios.paused){
                        sessionStorage.setItem('currentPausedTime',audios.currentTime);
                        audios.pause();
                    }else{
                        sessionStorage.setItem('currentPlayTime',audios.currentTime);                        
                    }
                }
            }
            function loadCurrentSetting(){
                
                var player = document.getElementById("dynamic_player");
                if (player.style.display != 'none'){
                    player.style.display = 'none';
                    document.getElementsByClassName('openClose')[0].src = 'img/expand.png';
                    var control = document.getElementById("dynamic_controls");
                    control.style.position = 'fixed';
                    control.style.bottom = '0px';
                    control.style.right = '0px';
                }

                var audios = document.getElementById('masterPlayer');
                if (sessionStorage.getItem('currentSRC')!=null){
                    audios.src = sessionStorage.getItem('currentSRC');
                    if (sessionStorage.getItem('currentPlayTime')!=null){                        
                        audios.addEventListener('loadedmetadata', function(){this.currentTime=sessionStorage.getItem('currentPlayTime');},false);
                        audios.play();
                        if (sessionStorage.getItem('itemBefore')!=null){
                            document.getElementById(sessionStorage.getItem('itemBefore')).style.backgroundImage = 'url(img/dynamicItemPlaying.jpg)';
                        }
                    }else if(sessionStorage.getItem('currentPausedTime')!=null){
                        audios.addEventListener('loadedmetadata', function(){this.currentTime=sessionStorage.getItem('currentPausedTime');},false);                                                                    
                    }
                    if (sessionStorage.getItem('itemBefore')!=null){
                        document.getElementById(sessionStorage.getItem('itemBefore')).style.backgroundImage = 'url(img/dynamicItemPlaying.jpg)';
                    }
                }
            }
            function resetSetting(){
                sessionStorage.removeItem('currentSRC');
                sessionStorage.removeItem('currentPlayTime');
                sessionStorage.removeItem('currentPausedTime');
            }
            function addToPlaylist(){
                if (songInDynamicPlayer.length!=0){
                    var playlist = '';
                    for (var i =0;i<songInDynamicPlayer.length;i++){
                        if (i!=songInDynamicPlayer.length-1){
                            playlist+=songInDynamicPlayer[i].songID+'|';
                        }else playlist+=songInDynamicPlayer[i].songID;
                    }                    
                    var xmlHttp = getXMLHttpRequest();

                    xmlHttp.onreadystatechange=function(){
                        if (xmlHttp.readyState==4 && xmlHttp.status==200)                     
                        {
                            var xml = xmlHttp.responseXML;
                            if (xml!=null){                                

                            }
                            else{
                                
                            }

                        } // end if
                    } // end function

                    xmlHttp.open("POST","CreateDyamicPlaylist?playlist="+playlist,true);
                    xmlHttp.send();                                           
                }
            }
        </script>
    </head>
    <body onunload="saveCurrentSetting()">

        <div id="bottom">
            <div id ="bottom_content"></div>
            <div id="player_bar" >

                <div id="dynamic_controls"><div class="subDragZone" ondragover="allowDrop(event)" ondrop="drop(event)">Kéo thả bài hát ở đây để nghe</div>
                    <audio preload="metadata"  preload="none" id="masterPlayer" classs="masterControl" controls></audio><img src="img/nextButton.png" onclick="nextFunction()" title="Bài sau" /><img src="img/backButton.png" onclick="backFunction()" title="Bài trước"/><img onclick="addToPlaylist()" src="img/addToPlaylist.png" /><img class="openClose" src="img/collapse.png" title="Mở rộng" onclick="expandCollapsed()"/>
                </div>
                <div id="dynamic_player" ondragover="allowDrop(event)" ondrop="drop(event)">
                </div>
            </div>
        </div>
        <script>
            setEventForSong();
            loadSongData();            
            document.getElementById('masterPlayer').addEventListener('ended', eventEndSong, false);
            document.getElementById('masterPlayer').addEventListener("play", function(){
                var pageVideoPlayers = document.getElementsByTagName("video");
                for (var i=0;i<pageVideoPlayers.length;i++){
                    if (pageVideoPlayers[i].play){
                        pageVideoPlayers[i].pause();
                    }
                }
                var pageAudioPlayers = document.getElementsByTagName("audio");
                for (var i=0;i<pageAudioPlayers.length;i++){
                    if ((pageAudioPlayers[i].getAttribute("id")!=null)||typeof((pageAudioPlayers[i].getAttribute("id"))=='undefined')){
                        if (pageAudioPlayers[i].getAttribute("id")!='masterPlayer'){
                            if (pageAudioPlayers[i].play){
                                pageAudioPlayers[i].pause();
                            }
                        }
                    }
                }
            }, false);
    
            loadCurrentSetting();
        </script>
    </body>
</html>
